<?php

/**
 * Created by PhpStorm.
 * Script Name: Setting.php
 * Create: 2020/5/24 上午10:25
 * Description: 站点配置
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace app\admin\controller;
use app\common\model\Keyword as KeywordM;
use app\constants\Common;
use app\constants\Media;
use app\constants\Reply as ReplyConst;

class Keyword extends Botbase
{
    /**
     * @var KeywordM
     */
    protected $model;
    private $tabList;
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new KeywordM();
        $events = ReplyConst::events();
        foreach ($events as $k => $v){
            $this->tabList[$k] = [
                'title' => $events[$k],
                'href' => url('index', ['event' => $k])
            ];
        }
    }

    /**
     * 设置
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @author: fudaoji<fdj@kuryun.cn>
     */
    public function index(){
        if (request()->isPost()) {
            $post_data = input('post.');
            $where = ['admin_id' => $this->adminInfo['id'], 'bot_id' => $this->bot['id']];
            !empty($post_data['search_key']) && $where['keyword'] = ['like', '%' . $post_data['search_key'] . '%'];
            $total = $this->model->total($where, true);
            if ($total) {
                $list = $this->model->getList(
                    [$post_data['page'], $post_data['limit']], $where,
                    ['id' => 'desc'], true, true
                );
                foreach ($list as $k => $v){
                    if($material = model('media_' . $v['media_type'])->getOneByMap([
                        'admin_id' => $v['admin_id'],
                        'id' => $v['media_id']
                    ], true, true)){
                        $v['media_title'] = $v['media_type'] == 'text' ? $material['content'] : $material['title'];
                    }
                    $list[$k] = $v;
                }
            } else {
                $list = [];
            }
            $this->success('success', '', ['total' => $total, 'list' => $list]);
        }

        $builder = new ListBuilder();
        $builder->setSearch([
                ['type' => 'text', 'name' => 'search_key', 'title' => '关键词']
            ])
            ->addTopButton('addnew')
            ->addTopButton('addnew', ['title' => '从其他机器人复制', 'href' => url('copy'), 'class' => 'layui-btn layui-btn-sm'])
            ->addTopButton('forbid')
            ->addTableColumn(['title' => '', 'type' => 'checkbox'])
            ->addTableColumn(['title' => '关键词', 'field' => 'keyword', 'minWidth' => 100])
            ->addTableColumn(['title' => '回复类型', 'field' => 'media_type', 'minWidth' => 100])
            ->addTableColumn(['title' => '回复内容', 'field' => 'media_title', 'minWidth' => 100])
            ->addTableColumn(['title' => '批量指定', 'field' => 'user_type', 'type' => 'enum','options' => \app\constants\Task::userTypes(),'minWidth' => 100])
            ->addTableColumn(['title' => '自由指定', 'field' => 'wxids', 'minWidth' => 100])
            ->addTableColumn(['title' => '状态', 'field' => 'status', 'minWidth' => 50, 'type' => 'switch', 'options' => Common::status()])
            ->addTableColumn(['title' => '创建时间', 'field' => 'create_time', 'type' => 'datetime', 'minWidth' => 170])
            ->addTableColumn(['title' => '修改时间', 'field' => 'update_time', 'type' => 'datetime', 'minWidth' => 170])
            ->addTableColumn(['title' => '操作', 'minWidth' => 150, 'type' => 'toolbar'])
            ->addRightButton('edit')
            ->addRightButton('delete');
        return $builder->show();
    }

    public function copy()
    {
        if(request()->isPost()){
            $post_data = input('post.');
            $exists = $this->model->getField(['keyword'], ['bot_id' => $this->bot['id']]);
            $list = $this->model->getAll([
                'where' => ['bot_id' => $post_data['bot_id'], 'status' => 1, 'keyword' => ['notin', count($exists) ? $exists : [0]]],
                'refresh' => true
            ]);
            foreach ($list as $v){
                unset($v['id']);
                $v['bot_id'] = $this->bot['id'];
                $v['wxids'] = '';
                $this->model->addOne($v);
            }
            $this->success('操作成功', '/undefined');
        }
        $bot_list = $this->getBots(['id' => ['<>', $this->bot['id']]]);
        // 使用FormBuilder快速建立表单页面
        $builder = new FormBuilder();
        $builder->setMetaTitle('复制内容')
            ->setPostUrl(url('copy'))
            ->addFormItem('bot_id', 'chosen', '机器人', '请选择', $bot_list, 'required');

        return $builder->show();
    }

    public function add()
    {
        $material = [];
        $members = $this->getMembers();
        // 使用FormBuilder快速建立表单页面
        $builder = new FormBuilder();
        $builder->setMetaTitle('新增')
            ->setPostUrl(url('savePost'))
            ->addFormItem('keyword', 'text', '关键词', '多个关键词用|分割', [], 'required maxlength=200')
            ->addFormItem('media', 'choose_media', '选择素材', '选择素材', ['types' => \app\constants\Media::types()], 'required')
            ->addFormItem('need_at', 'radio', '艾特提问者', '在群聊中是否艾特提问者', [0 => '否', 1 => '是'], 'required')
            ->addFormItem('zddx_legend', 'legend', '指定对象', '指定对象')
            ->addFormItem('user_type', 'radio', '批量选择', '批量选择', \app\constants\Task::userTypes())
            ->addFormItem('wxids', 'chosen_multi', '自由选择', '此处若填写，会覆盖批量选择的值', $members)
            ->setFormData(['need_at' => 0]);

        return $builder->show(['material' => $material]);
    }

    public function edit()
    {
        $id = input('id', null);
        $data = $this->model->getOneByMap(['id' => $id, 'admin_id' => $this->adminInfo['id']], true, true);

        if (!$data) {
            $this->error('参数错误');
        }
        $data['wxids'] = empty($data['wxids']) ? [] : explode(',', $data['wxids']);
        $material = model('media_' . $data['media_type'])->getOneByMap([
            'admin_id' => $data['admin_id'],
            'id' => $data['media_id']
        ], true, true);

        $members = $this->getMembers();
        // 使用FormBuilder快速建立表单页面
        $builder = new FormBuilder();
        $builder->setMetaTitle('编辑')
            ->setPostUrl(url('savePost'))
            ->addFormItem('id', 'hidden', 'ID', 'ID')
            ->addFormItem('keyword', 'text', '关键词', '编辑状态不支持多个关键词', [], 'required maxlength=30')
            ->addFormItem('media', 'choose_media', '选择素材', '选择素材', ['types' => \app\constants\Media::types(), 'id' => $data['media_id'], 'type' => $data['media_type']], 'required')
            ->addFormItem('need_at', 'radio', '艾特提问者', '在群聊中是否艾特提问者', [0 => '否', 1 => '是'], 'required')
            ->addFormItem('sort', 'number', '排序', '数字越大优先级越高', [], 'required min=0')
            ->addFormItem('status', 'radio', '状态', '状态', [1 => '启用', 0 => '禁用'])
            ->addFormItem('zddx_legend', 'legend', '指定对象', '指定对象')
            ->addFormItem('user_type', 'radio', '批量选择', '批量选择', \app\constants\Task::userTypes())
            ->addFormItem('wxids', 'chosen_multi', '自由选择', '此处若填写，会覆盖批量选择的值', $members)
            ->setFormData($data);

        return $builder->show(['material' => $material]);
    }

    public function savePost($jump_to = '/undefined', $data = [])
    {
        $post_data = input('post.');
        $post_data['bot_id'] = $this->bot['id'];
        $keywords = trim($post_data['keyword'], '|');
        $keyword_arr = explode('|', $keywords);
        if(empty($post_data[$this->pk])){
            $post_data['admin_id'] = $this->adminInfo['id'];
            foreach ($keyword_arr as $keyword){
                $post_data['keyword'] = $keyword;
                $this->model->addOne($post_data);
            }
        }else {
            $this->model->updateOne($post_data);
        }
        foreach ($keyword_arr as $keyword){
            //refresh
            $this->model->getAll([
                'order' => ['sort' => 'desc'],
                'where' => [
                    'bot_id' => $this->bot['id'],
                    'keyword' => $keyword,
                    'status' => 1
                ],
                'refresh' => true
            ]);
        }
        $this->success('数据保存成功', $jump_to);
    }
}